package com.hrsaas.ext.spider.core.url;

import java.net.URLDecoder;

import com.hrsaas.ext.spider.util.Assert;

/**
 * <p>
 * 功能：解析请求参数
 * <p>
 * 
 * @author wangxiaoliang@kanzhun.com
 *
 *         2018年8月1日
 */
public final class ParametersElement {
	private final String value;
	private final String key;
	public static final ParametersElement EMPTY = new ParametersElement();

	public ParametersElement(String key, String value) {
		this.key = key;
		this.value = value;
		// One may be null but not both
		if (key == null && value == null) {
			Assert.notNull("key and value", key);
		}
	}

	private ParametersElement() {
		key = null;
		value = null;
	}

	public static ParametersElement parse(String queryString) {
		Assert.notNull("qeString", queryString);
		int ix = queryString.indexOf('=');
		if (ix == 0 && queryString.length() > 1) {
			return new ParametersElement(null, queryString);
		} else if (ix < 0) {
			return new ParametersElement(queryString, null);
		} else if (queryString.length() > 0) {
			String key = queryString.substring(0, ix);
			String val = queryString.substring(ix + 1);
			return new ParametersElement(key, val);
		} else {
			return new ParametersElement(queryString, null);
		}
	}

	public String getKey() {
		return key;
	}

	public String getValue() {
		return value;
	}

	public String decodedKey() {
		return URLDecoder.decode(key);
	}

	public String decodedValue() {
		return URLDecoder.decode(value);
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		appendTo(sb);
		return sb.toString();
	}

	public void appendTo(StringBuilder sb) {
		if (key != null) {
			URLBuilder.append(sb, key, ':', '?');
		}
		if (value != null) {
			sb.append('=');
		}
		if (value != null) {
			URLBuilder.append(sb, value, ':', '?');
		}
	}

}
